<template>
  <view class="mes-form">
    <view
      class="mes-form-item-group"
      :style="{ marginTop: mesForm.top ? mesForm.top + 'rpx' : 0 }"
    >
      <view
        class="mes-form-item"
        v-for="(item, index) in mesForm.items"
        :key="index"
        @tap="tapFormItem(item, $event)"
      >
        <mes-form-item :row="mesForm.row" :config="item"></mes-form-item>
      </view>
    </view>
  </view>
</template>

<script>
/**
 * 1. onMounted 时监听全局自定义事件 form-item-created，参数为表单规则验证函数
 * 2. onUnmounted 时移除监听全局自定义事件 form-item-created
 * 3. save 时先校验整个表单，再触发 save 事件，参数为表单校验结果 true OR false
 */

import { ref, onMounted, onUnmounted } from 'vue'

export default {
  props: {
    mesForm: Object
  },
  setup(props, context) {
    const funcArr = ref([])
    onMounted(() => {
      uni.$on('form-item-created', callback)
    })
    onUnmounted(() => {
      uni.$off('form-item-created', callback)
      funcArr.value = []
    })
    // 表单规则验证回调
    const callback = (func) => {
      funcArr.value.push(func)
    }
    // 校验整个表单
    const validate = (callback) => {
      const result = funcArr.value.every((func) => func())
      callback && callback(result)
    }
    // 保存
    const save = () => {
      validate((result) => {
        context.emit('save', result)
      })
    }

    // 点击 form-item
    const tapFormItem = (item, e) => {
      if (item.tap && !item.slots.is_detail) {
        item.tap()
        e.preventDefault()
      }
    }

    return {
      validate,
      save,
      tapFormItem
    }
  }
}
</script>

<style lang="less" scoped>
.mes-form-item-group {
  width: 702rpx;
  margin: 0 auto;
  background: #fff;
  border-radius: 16rpx;
  .mes-form-item {
    width: 638rpx;
    margin: 0 auto;
    border-bottom: 1px solid #eee;
    &:last-child {
      border-bottom: none;
    }
  }
}
</style>
